<?
require_once(dirname(__FILE__).'/../models/Users.php');
require_once(dirname(__FILE__).'/../models/Discussions.php');
require_once(dirname(__FILE__).'/../models/Comments.php');
require_once('IndexController.php');

class DiscussionsController extends IndexController {	
	public function preDispatch()
    {
    	parent::preDispatch();
        if (!$this->loggedUser->getId()) {        
                header('Location: /login');
        } else {
           /**
			 * Translation - Loading dictionaries common and backoffice_common
			 */
			$commonLocale = Translator::loadTranslation($this->currentLang, 'common');
			$this->view->commonLocale = $commonLocale;
        }
    }
	
	function indexAction(){
		
	}
	
	function addAction(){
		$this->view->uploadDestination = $this->config->uploads->discussions->origin_dir;
		$this->view->fileTypesId = $this->config->uploads->discussions->fileTypesId;
		
		$recipient = ModelMapper::instance('Users')->find(intval($this->_request->getParam('recipientId')));
		$this->view->date = date('Y-m-d H:i');
		$this->view->recipient = $recipient;
	}
	
	function saveAction(){
		//Database::instance()->getConn()->debug = 1;
		$formData = $this->_request->getParam('addForm');
		
		//debug($formData);
		if (intval($formData['discussionsId']) >0) {
			$obj = ModelMapper::instance('Discussions')->find(intval($formData['discussionsId']));
			//$mainImageId = $obj->getMainImageId();
		}
		else {
			$obj = new Discussions();
			//$mainImageId = NULL;
			$obj->setAppsId($this->apps['id']);
			$obj->setUsersId($this->loggedUser->getId());
			$obj->setRecipientId($formData['recipientId']);
			$obj->setStatusesId($this->config->statuses->general->active);
			$obj->setAddDate(date('Y-m-d H:i:s'));
			ObjectWatcher::flushOperations();
		}
		
		$comment = new Comments();
		$comment->setContentTypesId($this->config->contentTypes->discussionEntry);
		$comment->setObjectId($obj->getId());
		$comment->setUsersId($this->loggedUser->getId());
		$comment->setAddDate(date('Y-m-d H:i:s'));
		$comment->setContent(trim(strip_tags(stripcslashes($formData['content']))));
		ObjectWatcher::flushOperations();
		
		$obj->setLastCommentId($comment->getId());
		
		if (intval($formData['discussionsId']) == 0){
			$obj->setFirstCommentId($comment->getId());
		}
		header('Location: /account/inbox');
		exit();
	}
	
	function showAction(){
		$this->view->uploadDestination = $this->config->uploads->discussions->origin_dir;
		$this->view->fileTypesId = $this->config->uploads->discussions->fileTypesId;
		
		$discussion = ModelMapper::instance('Discussions')->find(intval($this->_request->getParam('discussionsId')));
		if (($discussion->getAuthor()->getId() != $this->loggedUser->getId()) && ($discussion->getRecipient()->getId() != $this->loggedUser->getId()))
			die('restricted');
			
		$this->view->discussion = $discussion;
	}

}

?>